package org.mclll.xwangplugin.questTracking.questGoal;

import me.pikamug.quests.events.quester.BukkitQuesterPostUpdateObjectiveEvent;
import me.pikamug.quests.player.Quester;
import me.pikamug.quests.quests.components.BukkitObjective;
import me.pikamug.quests.quests.components.Stage;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.scoreboard.Objective;
import org.jetbrains.annotations.NotNull;
import org.mclll.xwangplugin.questTracking.persistence.Persistence;

import java.util.LinkedList;
import java.util.List;

/**
 * @author: geduo
 * @date: 2023/10/13 15:01
 */
public class PasswordQuestTrack {

    public static void questTracking(Objective context, Integer line, Stage questsStage) {
        LinkedList<String> passwordDisplays = questsStage.getPasswordDisplays();
        if (passwordDisplays.isEmpty()) {
            return;
        }
        for (String passwordDisplay : passwordDisplays) {
            context.getScore(getGoalFormat(passwordDisplay)).setScore(line--);
        }
    }

    @NotNull
    public static String getGoalFormat(String passwordDisplay) {
        return ChatColor.YELLOW + passwordDisplay;
    }

    @NotNull
    public static String getFinishFormat(String passwordDisplay) {
        return ChatColor.GRAY + passwordDisplay + " (✓)";
    }

    public static void goalFinish(BukkitQuesterPostUpdateObjectiveEvent event, List<Persistence.SerializeScore> scoreboard) {
        BukkitObjective questsObj = (BukkitObjective) event.getObjective();
        String password = (String) questsObj.getGoalObject();
        String passwordDisplay = "";
        String entry = null;
        Quester quester = event.getQuester();
        Stage currentStage = quester.getCurrentStage(event.getQuest());
        for (int i = 0; i < currentStage.getPasswordPhrases().size(); i++) {
            String pass = currentStage.getPasswordPhrases().get(i);
            if (pass.equals(password)) {
                passwordDisplay = currentStage.getPasswordDisplays().get(i);
                entry = getGoalFormat(passwordDisplay);
                break;
            }
        }
        for (Persistence.SerializeScore item : scoreboard) {
            if (item.getName().equals(entry)) {
                item.setName(getFinishFormat(passwordDisplay));
                item.setValue(scoreboard.get(scoreboard.size() - 1).getValue() - 1);
            }
        }
    }


}
